<template>
  <el-breadcrumb separator="/">
    <el-breadcrumb-item>{{ $t('Home') }}</el-breadcrumb-item>
    <el-breadcrumb-item>{{ $t('Community') }}</el-breadcrumb-item>
    <el-breadcrumb-item>{{ $t('Post') }}</el-breadcrumb-item>
  </el-breadcrumb>

  <div class="post-detail">
    <!-- 文章主体部分 -->
    <div class="post-main">
      <el-card class="post-content" shadow="never">
        <div class="post-header">
          <h1 class="post-title">{{ post.title }}</h1>
          <div class="post-meta">
            <div class="post-stats">
              <span class="publish-time">{{ post.created_at }}</span>
              <span class="comments"><el-icon><ChatDotRound /></el-icon> {{ post.comment_count }}</span>
            </div>
          </div>
        </div>
        
        <div class="post-body" v-html="post.content"></div>

        <div class="post-footer">
          <div class="actions">
            <el-button @click="handleCollect" :class="{ active: isCollected }">
              <el-icon><Star /></el-icon> {{ post.collections }}
            </el-button>
            <el-button @click="handleShare">
              <el-icon><Share /></el-icon> 分享
            </el-button>
          </div>
        </div>
      </el-card>

      <!-- 评论区 -->
      <el-card class="comments-section" shadow="never">
        <template #header>
          <div class="comments-header">
            <span>评论 ({{ post.comment_count }})</span>
          </div>
        </template>

        <!-- 评论输入框 -->
        <div class="comment-input">
          <el-input
            v-model="newComment"
            type="textarea"
            :rows="3"
            placeholder="写下你的评论..."
          />
          <el-button type="primary" @click="submitComment" style="margin-top: 10px">
            发表评论
          </el-button>
        </div>

        <!-- 评论列表 -->
        <div class="comments-list">
          <div v-for="comment in comments" :key="comment.id" class="comment-item">
            <div class="comment-user">
              <el-avatar :src="comment.avatar" size="small" />
              <span class="username">{{ comment.username }}</span>
              <span class="time">{{ comment.time }}</span>
            </div>
            <div class="comment-content">{{ comment.content }}</div>
            <div class="comment-actions">
              <span @click="replyToComment(comment)">回复</span>
            </div>
            <!-- 回复列表 -->
            <div v-if="comment.replies && comment.replies.length" class="replies">
              <div v-for="reply in comment.replies" :key="reply.id" class="reply-item">
                <div class="comment-user">
                  <el-avatar :src="reply.avatar" size="small" />
                  <span class="username">{{ reply.username }}</span>
                  <span class="time">{{ reply.time }}</span>
                </div>
                <div class="comment-content">{{ reply.content }}</div>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 栏 -->
    <div class="post-sidebar">
      <el-card class="author-card" shadow="never">
        <div class="author-header">
          <el-avatar :src="author.avatar_url" :size="64" />
          <h3>{{ author.username }}</h3>
          <p class="author-bio">{{ author.bio }}</p>
        </div>
        <div class="author-stats">
          <div class="stat-item">
            <div class="number">{{ post.author_posts }}</div>
            <div class="label">文章</div>
          </div>
          <div class="stat-item">
            <div class="number">{{ post.author_followers }}</div>
            <div class="label">粉丝</div>
          </div>
        </div>
        <el-button type="primary" @click="followAuthor" :class="{ active: isFollowing }">
          {{ isFollowing ? '已关注' : '关注作者' }}
        </el-button>
      </el-card>

      <el-card class="related-posts" shadow="never">
        <template #header>
          <div class="card-header">
            <span>相关文章</span>
          </div>
        </template>
        <div v-for="item in relatedPosts" :key="item.id" class="related-item">
          <router-link :to="`/post/${item.id}`">{{ item.title }}</router-link>
          <div class="related-meta">{{ item.comment_count }} 评论</div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { config } from '@/config/config';
import ApiClient from '@/api/ApiClient';
import { ApiRequest, ApiRequestBody } from '@/api/ApiRequest';
import { ApiResponse } from '@/api/ApiResponse';

const route = useRoute();

// 定义文章接口
interface Post {
  post_id: string;
  community_id: string;
  account_address: string;
  cover_url: string;
  title: string;
  summary: string;
  content: string;
  created_at: string;
  updated_at: string;
}

// 在现有的接口定义后添加作者信息接口
interface Author {
  account_address: string;
  username: string;
  avatar_url: string;
  bio: string;
  created_at: string;
  updated_at: string;
}

// 修改 post 的定义
const post = reactive<Post>({
  post_id: '',
  community_id: '',
  account_address: '',
  cover_url: '',
  title: '',
  summary: '',
  content: '',
  created_at: '',
  updated_at: ''
});

// 在 setup 中添加作者信息的响应式数据
const author = reactive<Author>({
  account_address: '',
  username: '',
  avatar_url: '',
  bio: '',
  created_at: '',
  updated_at: ''
});

const comments = ref([
  {
    id: 1,
    username: '技术爱好者',
    avatar: 'http://38.6.216.42:8080/ipfs/QmSA7aiiKyyewfFDWRew4G5GcdPEAWiJAtRxUtGnWvYivG',
    content: '文章写得非常好，对DAO的解释很清晰！',
    time: '2024-03-20 15:00:00',
    replies: [
      {
        id: 11,
        username: '区块链专家',
        avatar: 'http://38.6.216.42:8080/ipfs/QmSA7aiiKyyewfFDWRew4G5GcdPEAWiJAtRxUtGnWvYivG',
        content: '感谢支持！',
        time: '2024-03-20 15:05:00'
      }
    ]
  },
  {
    id: 2,
    username: '区块链研究者',
    avatar: 'http://38.6.216.42:8080/ipfs/QmSA7aiiKyyewfFDWRew4G5GcdPEAWiJAtRxUtGnWvYivG',
    content: '对技术实现部分还可以展开讨论一下',
    time: '2024-03-20 16:00:00',
    replies: []
  }
]);

const relatedPosts = ref([
  {
    id: 2,
    title: '智能合约开发最佳实践',
    comment_count: 23
  },
  {
    id: 3,
    title: 'Web3.0生态系统概述',
    comment_count: 15
  },
  {
    id: 4,
    title: '去中心化存储解决方案',
    comment_count: 8
  }
]);

const newComment = ref('');
const isCollected = ref(false);
const isFollowing = ref(false);

// 添加获取作者信息的方法
const fetchAuthorInfo = async (accountAddress: string) => {
  const methodType = 'query';
  const methodName = 'get_users_by_addresses';
  const params = {
    addresses: `["${accountAddress}"]`
  };

  const request = new ApiRequest(
    methodType,
    config.dao_chain_name,
    new ApiRequestBody(
      config.dao_contract_name,
      methodName,
      params
    )
  );

  try {
    ApiClient.sendSync(request, (response: ApiResponse) => {
      const contractResult = response.data.contract_result;
      const result = JSON.parse(contractResult.result);
      
      if (Array.isArray(result) && result.length > 0) {
        const authorData = result[0];
        
        // 更新作者信息
        Object.assign(author, {
          ...authorData,
          avatar_url: config.getUrl(authorData.avatar_url),
          created_at: new Date(parseInt(authorData.created_at) * 1000).toLocaleString(),
          updated_at: new Date(parseInt(authorData.updated_at) * 1000).toLocaleString()
        });
      }
    });
  } catch (error) {
    console.error('获取作者信息失败:', error);
    ElMessage.error('获取作者信息失败，请稍后重试');
  }
};

// 添加获取文章详情的方法
const fetchPostDetail = async (postId: string) => {
  const methodType = 'query';
  const methodName = 'get_post';
  const params = {
    post_id: postId
  };

  const request = new ApiRequest(
    methodType,
    config.dao_chain_name,
    new ApiRequestBody(
      config.dao_contract_name,
      methodName,
      params
    )
  );

  try {
    ApiClient.sendSync(request, async (response: ApiResponse) => {
      const contractResult = response.data.contract_result;
      const result = JSON.parse(contractResult.result);
      
      if (Array.isArray(result) && result.length > 0) {
        const postData = result[0];
        
        // 处理content中的IPFS链接
        let processedContent = postData.content;
        if (processedContent) {
          // 使用正则表达式匹配ipfs://开头的链接
          processedContent = processedContent.replace(
            /ipfs:\/\/[a-zA-Z0-9]+/g, 
            (match) => match.replace('ipfs://', config.ipfs_gateway)
          );
        }

        // 更新文章数据
        Object.assign(post, {
          ...postData,
          content: processedContent,
          created_at: new Date(parseInt(postData.created_at) * 1000).toLocaleString(),
          updated_at: new Date(parseInt(postData.updated_at) * 1000).toLocaleString(),
          cover_url: config.getUrl(postData.cover_url)
        });

        // 获取作者信息
        await fetchAuthorInfo(postData.account_address);
      }
    });
  } catch (error) {
    console.error('获取文章详情失败:', error);
    ElMessage.error('获取文章详情失败，请稍后重试');
  }
};

// 修改 onMounted 钩子
onMounted(async () => {
  const postId = route.params.id as string;
  if (!postId) {
    ElMessage.error('文章ID不存在');
    return;
  }

  try {
    await fetchPostDetail(postId);
    // 其他数据加载
    await Promise.all([
      fetchComments(postId),
      fetchRelatedPosts(postId)
    ]);
  } catch (error) {
    console.error('加载文章失败:', error);
    ElMessage.error('加载文章失败，请稍后重试');
  }
});

const fetchComments = async (postId: string) => {
  console.log('获取评论列表:', postId);
  // 实际项目中这��会调用API
};

const fetchRelatedPosts = async (postId: string) => {
  console.log('获取相关文章:', postId);
  // 实际项目中这里会调用API
};

const handleCollect = () => {
  isCollected.value = !isCollected.value;
  if (isCollected.value) {
    post.collections++;
    ElMessage.success('收藏成功');
  } else {
    post.collections--;
    ElMessage.success('取消收藏');
  }
};

const handleShare = () => {
  // 获取当前文章的完整URL
  const url = window.location.href;
  
  // 使用 navigator.clipboard API 复制到剪贴板
  navigator.clipboard.writeText(url)
    .then(() => {
      ElMessage.success('链接已复制到剪贴板');
    })
    .catch(() => {
      // 如果clipboard API失败，使用传统方法
      const textarea = document.createElement('textarea');
      textarea.value = url;
      document.body.appendChild(textarea);
      textarea.select();
      try {
        document.execCommand('copy');
        ElMessage.success('链接已复制到剪贴板');
      } catch (err) {
        ElMessage.error('复制失败，请手动复制');
      }
      document.body.removeChild(textarea);
    });
};

const submitComment = async () => {
  if (!newComment.value.trim()) {
    ElMessage.warning('请输入评论内容');
    return;
  }
  
  const newCommentObj = {
    id: comments.value.length + 1,
    username: '当前用户',
    avatar: 'http://38.6.216.42:8080/ipfs/QmSA7aiiKyyewfFDWRew4G5GcdPEAWiJAtRxUtGnWvYivG',
    content: newComment.value,
    time: new Date().toLocaleString(),
    replies: []
  };
  
  comments.value.unshift(newCommentObj);
  post.comment_count++;
  newComment.value = '';
  ElMessage.success('评论成功');
};

const followAuthor = async () => {
  isFollowing.value = !isFollowing.value;
  if (isFollowing.value) {
    post.author_followers++;
    ElMessage.success('关注成功');
  } else {
    post.author_followers--;
    ElMessage.success('取消关注');
  }
};

const replyToComment = (comment: any) => {
  ElMessage.info(`回复 ${comment.username} 的评论`);
};
</script>

<style scoped>
.post-detail {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
  display: flex;
  gap: 20px;
}

.post-main {
  flex: 1;
  min-width: 0;
}

.post-sidebar {
  width: 300px;
  flex-shrink: 0;
}

.post-content {
  margin-bottom: 20px;
}

.post-header {
  margin-bottom: 24px;
}

.post-title {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 16px;
  color: #2c3e50;
}

.post-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #8492a6;
}

.post-stats {
  display: flex;
  gap: 16px;
  align-items: center;
}

.post-body {
  font-size: 16px;
  line-height: 1.8;
  color: #2c3e50;
}

.post-footer {
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #ebeef5;
}

.actions {
  display: flex;
  gap: 12px;
}

.comments-section {
  margin-top: 20px;
}

.comment-item {
  padding: 16px 0;
  border-bottom: 1px solid #ebeef5;
}

.comment-user {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.comment-actions {
  margin-top: 8px;
  color: #8492a6;
  display: flex;
  gap: 16px;
}

.replies {
  margin-left: 48px;
  margin-top: 12px;
  padding-left: 12px;
  border-left: 2px solid #ebeef5;
}

.author-card {
  margin-bottom: 20px;
}

.author-header {
  text-align: center;
  margin-bottom: 16px;
}

.author-stats {
  display: flex;
  justify-content: space-around;
  margin: 16px 0;
}

.stat-item {
  text-align: center;
}

.number {
  font-size: 18px;
  font-weight: bold;
  color: #2c3e50;
}

.label {
  font-size: 12px;
  color: #8492a6;
}

.related-item {
  padding: 8px 0;
  border-bottom: 1px solid #ebeef5;
}

.related-meta {
  font-size: 12px;
  color: #8492a6;
  margin-top: 4px;
}

.publish-time {
  color: #8492a6;
  font-size: 14px;
}

.author-bio {
  color: #8492a6;
  font-size: 14px;
  margin-top: 8px;
}

@media (max-width: 768px) {
  .post-detail {
    flex-direction: column;
  }
  
  .post-sidebar {
    width: 100%;
  }
}
</style> 